package datos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
import javax.swing.JOptionPane;
import negocios.Usuario;

public class DatabaseManager {
    private Connection connection;
    private Savepoint svpt;
  
    public DatabaseManager() {
        try {
            String url = "jdbc:postgresql://localhost/TrabajoFinal?user=postgres&password=jorge";
            System.out.println(url);
            connection = DriverManager.getConnection(url);
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace(); }
     }

    public void commit() {
        try {
            connection.commit();
            svpt = connection.setSavepoint();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        return connection;
  
    }
    //en caso que necesite hacer conexiones paralelas

    public void openConnectionTo(String url) {
        try {
            connection = DriverManager.getConnection(url, "postgres", "clave");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
  
     public boolean grabarUSER(Usuario miuser, String ruta) {
        FileInputStream fis = null;
        try {
             File file = new File(ruta);
             fis = new FileInputStream(file);
             PreparedStatement pstm = connection.prepareStatement("INSERT INTO " + " usuario(cedula, apodo, fecha_nacimiento, id_genero, foto) " + " VALUES (?, ?, ?, ?, ?)");
             pstm.setString(1, miuser.getCedula());
             pstm.setString(2, miuser.getApodo());
             pstm.setString(3, miuser.getFecha_nacimiento());
             pstm.setInt(4, miuser.getGenero().getId());
             pstm.setBinaryStream(5, fis,(int) file.length());
             pstm.execute();
             pstm.close();
         return true;
        } catch (FileNotFoundException e) {
             System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
               fis.close();
             } catch (IOException e) {
               System.out.println(e.getMessage());
             }
        }
        return false;
        }  
    
    public void rollBack() {
        try {
            if (svpt != null) {
                connection.rollback(svpt);
                connection.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
